package com.itheima.Servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //拿到配置文件中的用户登录信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");
        //从session中取出正确的验证码信息
        HttpSession session = req.getSession();
        String checkCode1 = (String) session.getAttribute("checkCode");
            if(checkCode.equalsIgnoreCase(checkCode1)){
                System.out.println("验证码正确,开始比较用户名密码...");
                //1.如果验证码正确 开始比较用户名 密码
                //2.得到登录配置的文件路径的绝对路径
                ServletContext context = getServletContext();
                String realPath = context.getRealPath("/WEB-INF/classes/user.properties");

                //3.定义Properties集合
                Properties prop = new Properties();
                prop.load(new FileReader(realPath));

                if(prop.containsKey(username)&&password.equals(prop.getProperty(username))){
                    HttpSession session1 = req.getSession();
                    Cookie cookie = new Cookie("JSESSIONID",session1.getId());
                    cookie.setMaxAge(60*10);
                    session1.setAttribute("username",username);
                    resp.addCookie(cookie);
                    //重定向到查看页面
                    resp.sendRedirect(req.getContextPath()+"/stu/findAllStudent");
                }else{
                    //如果用户名密码错误
                    //重定向到登录页面
                    System.out.println("用户名或密码错误...");
                    resp.sendRedirect(req.getContextPath()+"/Login.html");
                }

            }else{
                //验证码错误 重定向到登录页面
                System.out.println("验证码错误,请重新输入...");
                resp.sendRedirect(req.getContextPath()+"/Login.html");
            }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
